﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using System.Reflection;
using System.Collections.Generic;
using socket_client.Transport_Protocol;

namespace socket_client
{
    class Program
    {
        private static Socket clientSocket;
        private static string IP = "10.246.34.190";//"192.168.56.1";
        private static int Port = 30000;
        private static CBindCmd cBindCmd = new CBindCmd();
        private static Dictionary<int, string> CM_Dictionary = new Dictionary<int, string>();
        private static Dictionary<int, string> SM_Dictionary = new Dictionary<int, string>();
        private static string CBaseRemoteEndPointStr;
        static void Main(string[] args)
        {
            CM_Dictionary = cBindCmd.GetCM_Dictionary();
            SM_Dictionary = cBindCmd.GetSM_Dictionary();
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //连接
            Connect();
        }

        //连接客户端，连接后开始监听发送过来的消息并且把输入的信息发给服务端
        public static void Connect()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                IPAddress Address = IPAddress.Parse(IP);
                //连接
                clientSocket.Connect(new IPEndPoint(Address, Port));

                //独立线程来接受来自服务端的数据
                Thread receive = new Thread(Receive);
                receive.Start(clientSocket);

                //独立线程来发送数据给服务端
                Thread send = new Thread(Send);
                send.Start(clientSocket);

                //独立线程来Ping服务端
                //Thread ping = new Thread(Ping);
                //ping.Start(clientSocket);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static void Receive(object so)
        {
            Socket clientSocket = so as Socket;

            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024];
                    int len = clientSocket.Receive(buffer);
                    if (len == 0) break;

                    string msg = Encoding.UTF8.GetString(buffer, 0, len);
                    Console.WriteLine("");
                    Console.WriteLine("***以下是服务端发送内容***" + "***当前时间：" + DateTime.Now.ToString() + "***");
                    Console.WriteLine("服务端说：" + msg);
                    CBaseClass cBaseClass = JsonConvert.DeserializeObject<CBaseClass>(msg);
                    if (cBaseClass != null)
                    {
                        string TypeName = SM_Dictionary[cBaseClass.CBaseClassID];
                        if (!string.IsNullOrEmpty(TypeName))
                        {
                            var SM_Msg = JsonConvert.DeserializeObject(msg, Type.GetType(TypeName));
                            if (SM_Msg is CSM_Test)
                            {
                                CSM_Test cSM_Test = (CSM_Test)SM_Msg;
                                Console.WriteLine("服务端说：" + cSM_Test.Desc);
                            }
                            else if (SM_Msg is CSM_SetCBaseRemoteEndPointStr)
                            {
                                CSM_SetCBaseRemoteEndPointStr cSM_SetCBaseRemoteEndPointStr = (CSM_SetCBaseRemoteEndPointStr)SM_Msg;
                                CBaseRemoteEndPointStr = cSM_SetCBaseRemoteEndPointStr.CBaseRemoteEndPointStr;
                            }
                        }
                    }
                    Console.WriteLine("***以上是服务端发送内容***" + "***当前时间：" + DateTime.Now.ToString() + "***");
                    Console.WriteLine("");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    break;
                }
            }
            clientSocket.Close();
            System.Environment.Exit(0);
        }

        public static void Send(object so)
        {
            Socket clientSocket = so as Socket;

            while (true)  // 监听键盘输入
            {
                //获取键盘输入
                string input = Console.ReadLine();

                if (input == "CCM_Test")
                {
                    CCM_Test cCM_Test = new CCM_Test()
                    {
                        CBaseClassID = CClientToServerClass.CM_Test,
                        CBaseRemoteEndPointStr = CBaseRemoteEndPointStr,
                        Desc = input,
                    };
                    //序列化为Json格式
                    string json = JsonConvert.SerializeObject(cCM_Test, Formatting.None);
                    //编码
                    byte[] buffer = Encoding.UTF8.GetBytes(json);
                    //发送
                    clientSocket.Send(buffer);
                }
                else if (input == "CCM_Fruit")
                {
                    CCM_Fruit cCM_Fruit = new CCM_Fruit()
                    {
                        CBaseClassID = CClientToServerClass.CM_Fruit,
                        CBaseRemoteEndPointStr = CBaseRemoteEndPointStr,
                        Name = "apple",
                        Price = 5.9f,
                        color = Color.red,
                    };
                    //序列化为Json格式
                    string json = JsonConvert.SerializeObject(cCM_Fruit, Formatting.None);
                    //编码
                    byte[] buffer = Encoding.UTF8.GetBytes(json);
                    //发送
                    clientSocket.Send(buffer);
                }
                else if (input == "CCM_QueryBag")
                {
                    Random random = new Random();
                    CCM_QueryBag cCM_QueryBag = new CCM_QueryBag()
                    {
                        CBaseClassID = CClientToServerClass.CM_QueryBag,
                        CBaseRemoteEndPointStr = CBaseRemoteEndPointStr,
                        UserID = random.Next(2100000000),
                    };
                    //序列化为Json格式
                    string json = JsonConvert.SerializeObject(cCM_QueryBag, Formatting.None);
                    //编码
                    byte[] buffer = Encoding.UTF8.GetBytes(json);
                    //发送
                    clientSocket.Send(buffer);
                }
                else
                {
                    CCM_Say cCM_Say = new CCM_Say()
                    {
                        CBaseClassID = CClientToServerClass.CM_Say,
                        CBaseRemoteEndPointStr = CBaseRemoteEndPointStr,
                        Say_Content = input,
                    };
                    //序列化为Json格式
                    string json = JsonConvert.SerializeObject(cCM_Say, Formatting.None);
                    //编码
                    byte[] buffer = Encoding.UTF8.GetBytes(json);
                    //发送
                    clientSocket.Send(buffer);
                }
            }
        }

        public static void Ping(object so)
        {
            Socket clientSocket = so as Socket;

            while (true)  // 监听键盘输入
            {
                Console.ForegroundColor = ConsoleColor.Red;
                //获取键盘输入
                string input = "当前时间为：" + DateTime.Now.ToString();
                //编码
                byte[] buffer = Encoding.UTF8.GetBytes(input);
                //发送
                clientSocket.Send(buffer);

                Thread.Sleep(10000);
            }
        }
    }
}
